﻿
var ns, toast, actionsheet, UIAlbumBrowser;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            ID: 0,
            RoomID: 0,
            ServiceArea: '个人区域',//个人区域、公共区域
            ServiceTypeID: '',//---工单类型ID
            ServiceTypeName: '',//---工单类型名称
            // ProjectName: '',
            ProjectID: '',
            ServiceFullName: '',//报修位置
            AddCallPhone: '',//报修人联系电话
            AppointTime: '',//预约开始时间
            AppointEndTime:'',//预约结束时间
            ServiceContent: '',//报修内容
            ServiceType: 'bsbx',
            AddCustomerName: '',//报修人
            action: 'creatsuctomerservice',
            Type: 2,
            PublicProjectID: 0
        },
        imglist: [],
        imgindex: 0,
        img_count: 0,
        select_imglist: [],
        select_imgindex: 0,
        maxuploadcount: CONFIG.maxuploadcount,
        //预约时间
        showTimePicker:false,
         // 时间相关选择
         TimeModel: {},
         TimeList: [
             { ID: 1, StartTime: '09:00', EndTime: '12:00', },
             { ID: 2, StartTime: '12:00', EndTime: '14:00', },
             { ID: 3, StartTime: '14:00', EndTime: '18:00', },
             { ID: 4, StartTime: '18:00', EndTime: '22:00', },
         ],
         // 日期选择
         dayModel: {},
         dayList: [],
         activeTime:0,
         filelist:[],
    },
    methods: {
        do_save: function (item) {
            var that = this;
            if (!that.form.ServiceTypeID) {
                api.toast({
                    msg: '请选择工单类型',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (!that.form.ServiceFullName) {
                api.toast({
                    msg: '请选择报修位置',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (!that.form.AddCustomerName) {
                api.toast({
                    msg: '请填写报修人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }



            // if (that.form.AddCallPhone == "") {
            //     api.toast({
            //         msg: '请填写电话',
            //         duration: 2000,
            //         location: 'bottom'
            //     });
            //     return;
            // }
            // if (that.form.AppointTime == "") {
            //     api.toast({
            //         msg: '请填写预约时间',
            //         duration: 2000,
            //         location: 'bottom'
            //     });
            //     return;
            // }



            if (that.form.ServiceContent == "") {
                api.toast({
                    msg: '请填写报事内容',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }

            // var filelist = [];
            // for (var i = 0; i < that.imglist.length; i++) {
            //     that.do_imageFilter(that.imglist[i].url);
            // }
            // setTimeout(() => {
                
            // }, 5000);
            toast.loading({
                title: "提交中",
                duration: 2000
            }, function (ret) { });
            ns.post(that.form, function (succeed, data, err) {
                toast.hide();
                that.is_searching = false;
                if (succeed) {
                    that.form.ProjectID = 0;
                    that.form.ServiceFullName = '';
                    that.form.ServiceTypeName = '';
                    that.form.AddCustomerName = '';
                    that.form.AddCallPhone = '';
                    that.form.AppointTime = '';
                    that.form.ServiceContent = '';
                    that.imglist = [];
                    that.imgindex = 0;
                    app.set_default();
                    api.sendEvent({
                        name: 'home_new_updata',
                        extra: {
                            key1: 'value1',
                        }
                    });
                    api.toast({
                        msg: '提交成功',
                        duration: 2000,
                        location: 'bottom'
                    });

                    api.closeWin();

                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                files: {
                    file: that.filelist
                }
            });
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start: function () {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function (ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath
                    });
                    that.imgindex++;
                }
            });
            return;
        },
        UIAlbumBrowser_transPath: function () {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path,
            }, function (ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.do_imageFilter(ret.path);
                    that.imglist.push({
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath
                    });
                    that.imgindex++;
                }
            });
        },
        //图片压缩
        do_imageFilter:function(path){
            var that=this;
            var imgName = Date.now() + '.jpg';
            var imgFullName = 'fs://photo/' + imgName;
            var imageFilter = api.require('imageFilter');
            imageFilter.compress({
                img: path,
                isClarityimg:false,
                quality: 0.2,
                scale:0.5,
                save: {
                    album: true,
                    imgPath: 'fs://photo/',
                    imgName: imgName
                },
            },function( ret, err ){      
                if( ret.status ){
                    // imageFilter.getAttr({
                    //     path:'fs://photo/'+imgName
                    // }, function(ret){
                    //     alert('获取'+JSON.stringify(ret));
                    // })
                    // console.log(JSON.stringify(imgFullName));
                    that.filelist.push(imgFullName);
                }else{
                    alert( JSON.stringify( err ) );
                }
            });
        },
        do_choose_type: function () {
            var that = this;
            ns.openWin('neibubaoshi_typelist', '工单类型选择', {
                gongdanType: 1,
            });
        },
        remove_img: function (index) {
            var that = this;
            for (var i = 0; i < that.imglist.length; i++) {
                var item = that.imglist[i];
                if (item.index == index) {
                    that.imglist.splice(i, 1);
                }
            }

        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        set_default: function () {
            api.getPrefs({
                key: 'username'
            }, function (ret, err) {
                if (ret.value) {
                    app.form.AddUserMan = ret.value;
                }
            });
            api.getPrefs({
                key: 'phonenumber'
            }, function (ret, err) {
                if (ret.value) {
                    app.form.PhoneNo = ret.value;
                }
            });
        },
        do_select_area: function (type) {
            var that = this;
            if (type == 1) {
                that.form.ServiceArea = '公共区域'
            }
            if (type == 2) {
                that.form.ServiceArea = '个人区域';
            }
            if (type == 2 && that.form.ServiceArea == '个人区域') {
                setTimeout(function () {
                    that.initPicker();//下拉数据
                }, 100);
            }
        },
        do_select_time: function () {
            var that = this;
            api.openPicker({
                type: 'date',
                date: that.form.AppointTime,
                title: '选择日期'
            }, function (ret, err) {
                if (ret) {
                    var year = ret.year;
                    var month = (ret.month >= 10 ? ret.month : '0' + ret.month);
                    var day = (ret.day >= 10 ? ret.day : '0' + ret.day);
                    api.openPicker({
                        type: 'time',
                        title: '选择时间'
                    }, function (ret2, err2) {
                        if (ret2) {
                            var hour = (ret2.hour >= 10 ? ret2.hour : '0' + ret2.hour);
                            var minute = (ret2.minute >= 10 ? ret2.minute : '0' + ret2.minute);
                            that.form.AppointTime = year + '-' +
                                month + '-' +
                                day + ' ' + hour + ':' + minute;
                        }
                    });
                }
            });
        },
        do_select_project: function () {
            var that = this;
            ns.openWin('chooseproject_frm', '选择项目');
        },
        get_select_project: function (data) {
            var that = this;
            if (data.projectid > 0) {
                that.form.RoomID = data.projectid;
            } else {
                that.form.RoomID = data.roomid;
            }
            that.form.ProjectID = data.projectid;
            that.form.ProjectName = data.name;
            that.form.ServiceFullName = data.name;
            that.getRoomOwner();
        },
        getRoomOwner: function () {
            var that = this;
            if(!that.form.RoomID){
                return;
            }
            ns.get({ action: 'getroomrelationdata', ProjectID: that.form.RoomID }, function (succeed, data, err) {
                if (succeed) {
                    if (!data.isRoom) {
                        that.form.ServiceArea = '公共区域';
                    }else{
                        that.form.ServiceArea = '个人区域';
                    }
                    that.form.AddCustomerName = data.RealName;
                    that.form.AddCallPhone = data.PhoneNumber;
                }
            });
        },
        do_select_type: function (type) {
            var that = this;
            that.form.Type = type;
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    var btn = document.querySelector('#choosedatetime');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            _self.picker.show(function (rs) {
                                _this.form.AppointTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.form.AppointTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);

                });
            })(mui, document);
        },
        getDate: function () {
            var that = this;
            var newdayList = [];
            var nowDateOne = that.getDateFormat(new Date(), 0);
            var nowDateTwo = that.getDateFormat(new Date(), 1);

            var dayOne = { ID: 1, Title: '今天', Week: '', Date: nowDateOne };
            dayOne.Week = that.getweekday(nowDateOne);

            var dayTwo = { ID: 2, Title: '明天', Week: '', Date: nowDateTwo };
            dayTwo.Week = that.getweekday(nowDateTwo);

            newdayList.push(dayOne);
            newdayList.push(dayTwo);

            that.dayModel = dayOne;//初始化
            that.dayList = newdayList;
            that.onDayChoose(that.dayList[0]);

        },
        getDateFormat: function (dt, addday) {
            var y = dt.getFullYear();
            var m = dt.getMonth() + 1;
            var d = dt.getDate() + addday;
            m = m < 10 ? '0' + m : m;
            var d = d < 10 ? '0' + d : d;
            return y + '-' + m + '-' + d;
        },
        getweekday: function (date) {
            var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
            var week = weekArray[new Date(date).getDay()];//注意此处必须是先new一个Date
            return week;
        },
        //选择预约时间
        onDayChoose(item) {
            var that = this;
            that.dayModel = item;
            that.TimeModel = {};
            that.form.AppointTime = '';
            that.form.AppointEndTime = '';
        },
        onTimeClick() {
            this.showTimePicker=!this.showTimePicker;
        },
        onTimeChoose(item) {
            this.form.AppointTime = this.dayModel.Date + " " + item.StartTime;
            this.form.AppointEndTime = this.dayModel.Date + " " + item.EndTime;
            this.TimeModel = item;
            this.onTimeClose();
        },
        onTimeClose() {
            this.showTimePicker=false;
        },

    }
});

apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    setTimeout(function () {
        app.form.AddCustomerName = api.getPrefs({
            sync: true,
            key: 'loginname'
        });
    }, 500)
    toast = new auiToast();
    actionsheet = new auiActionsheet();
    UIAlbumBrowser = api.require('UIAlbumBrowser');

    // app.getDate();//获取预约时间选择列表
    app.set_default();
    app.get_select_project(api.pageParam);
    api.addEventListener({
        name: 'do_choose_project_complete'
    }, function (ret) {
        app.get_select_project(ret.value);
    });
    api.addEventListener({
        name: 'dosaveservicetype'
    }, function (ret) {
        app.form.ServiceTypeName = ret.value.item.text;
        app.form.ServiceTypeID = ret.value.item.id;

    })
    api.addEventListener({
        name: 'do_open_neibubaoshi'
    }, function (ret, err) {
        ns.openWin('customerservice_history', '我的历史工单');
    });
    setTimeout(function () {
        api.sendEvent({
            name: 'do_close_equdetail',
        });
    }, 500)

};
